package com.example.module_hp_zao_yin_media.util;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import com.example.module_hp_zao_yin_media.activity.HpZaoYinPhotoActivity;
import com.example.module_hp_zao_yin_media.fragment.HpZaoYinPhotoFragment;

import java.lang.ref.WeakReference;

public class AudioRecordDemo2 {
    private static final String TAG = "AudioRecord";
    static final int SAMPLE_RATE_IN_HZ = 8000;
    static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ,
            AudioFormat.CHANNEL_IN_DEFAULT, AudioFormat.ENCODING_PCM_16BIT);
    AudioRecord mAudioRecord;
    boolean isGetVoiceRun;
    Object mLock;
    private WeakReference<HpZaoYinPhotoFragment> mActivity;

    public AudioRecordDemo2(HpZaoYinPhotoFragment activity) {
        mLock = new Object();
        mActivity = new WeakReference<>(activity);
    }

    public void stop() {
        this.isGetVoiceRun = false;
        if (mAudioRecord != null) {
            mAudioRecord.stop();
            mAudioRecord.release();
            mAudioRecord = null;
        }
        mActivity.clear(); // 清理弱引用
    }

    //对外暴露接口
    public interface MonitorInterface{
        void monitorListener(Double res);
    }

    public void getNoiseLevel(final MonitorInterface monitorInterface) {
        if (isGetVoiceRun) {
            return;
        }

        mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                SAMPLE_RATE_IN_HZ, AudioFormat.CHANNEL_IN_DEFAULT,
                AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE);

        if (mAudioRecord == null) {
            return;
        }

        isGetVoiceRun = true;

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mAudioRecord.startRecording();
                    short[] buffer = new short[BUFFER_SIZE];
                    final HpZaoYinPhotoFragment fragment = mActivity.get();

                    while (isGetVoiceRun) {
                        int r = mAudioRecord.read(buffer, 0, BUFFER_SIZE);
                        long v = 0;
                        for (int i = 0; i < buffer.length; i++) {
                            v += buffer[i] * buffer[i];
                        }
                        double mean = v / (double) r;
                        final double volume = 10 * Math.log10(mean);
                        Double res = Math.round(volume * 10) / 10.0;

                        if (fragment != null && fragment.isAdded() && fragment.isResumed()) {
                            fragment.requireActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    monitorInterface.monitorListener(res < 0 ? 0 : res);
                                }
                            });
                        } else {
                            break;
                        }

                        synchronized (mLock) {
                            try {
                                mLock.wait(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } finally {
                    // 确保即使异常也能停止录音
                    if (mAudioRecord != null) {
                        mAudioRecord.stop();
                        mAudioRecord.release();
                        mAudioRecord = null;
                    }
                    isGetVoiceRun = false;
                }
            }
        }).start();
    }


}
